package com.caiyouxi.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.common.Constant;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.finance.model.*;
import com.caiyouxi.finance.service.*;
import com.caiyouxi.goods.model.GoodsInfo;
import com.caiyouxi.goods.service.GoodsInfoService;
import com.caiyouxi.order.model.OrderBean;
import com.caiyouxi.order.service.OrderService;
import com.caiyouxi.restrict.service.RestrictedConditionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class CouponsPayService extends BaseService{
    @Autowired
    private RestrictedConditionService restrictedConditionService;
    @Autowired
    private GoodsInfoService goodsInfoService;
    @Autowired
    private FinanceTradeReceivedService financeTradeReceivedService;
    @Autowired
    private CouponsService couponsService;
    @Autowired
    private CouponBatchService couponBatchService;
    @Autowired
    private CouponTypeService couponTypeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private FinancePaymentDetailService financePaymentDetailService;
    @Autowired
    private FinanceTradeReceivableService financeTradeReceivableService;
    @Autowired
    private FinanceTradeDetailService financeTradeDetailService;


    /**
     * 券支付服务
     * @param trb
     * @param financeTradeReceivableList
     * @return
     */
    @Transactional
    public ResData couponsPay(FinanceTradeDetail trb, List<FinanceTradeReceivable> financeTradeReceivableList)
    {
       //1、检查该交易明细，如果状态不是PAYABLE（说明已经被支付、完成、被撤销或者已经被作废），则支付失败，返回错误提示；
        if(!"PAYABLE".equals(trb.getStatus())){
            //应付的（但是未收）PAYABLE
            Log.d("交易明细状态已支付、完成、被撤销或者被作废，无需用券");
            return failed(ErrorCode.SYS_FAIL);
        }

        //2、调用上文提到的券校验接口，如果接口返回结果中标识有不可以使用的券，则支付失败，直接返回；
        Integer tol_amount = trb.getTotal_amount();
        Integer end_amount = tol_amount;//剩余待支付
        OrderBean bean = orderService.get_order_by_id(trb.getTarget_id());
        JSONObject couponids = JSONObject.parseObject(bean.getCoupons_ids());//对应款项的券
        JSONObject jsons = JSONObject.parseObject(bean.getFund_json());
        Set<String> keys = jsons.keySet();
        GoodsInfo gInfo = goodsInfoService.select_goodsInfo_by_id(bean.getGoods_id().longValue());
        for(String key : keys){
            for(FinanceTradeReceivable ftr : financeTradeReceivableList){
                if(key.equals(ftr.getFund_type())){
                    String[] coupons_ids = couponsService.check_coupons(couponids.getString(key),key);
                    for(String coupons_id : coupons_ids){
                        if(end_amount != 0){
                            end_amount = coupons_on_use(coupons_id,key,end_amount,ftr.getFinance_trade_details_id(),ftr.getId(),bean.getBuyer_user_id(),gInfo,true);
                        }else{
                            //无需用券
                            Log.d(key + "无需用券");
                            break;
                        }
                    }
                }
                //更新应收应付记录流水状态
                ftr.setStatus(Constant.FINANCE_STATUS_RECEIVABLE);
                ftr.setUpdate_time(new Date());
                ftr.setFinished_amount(trb.getTotal_amount() - end_amount);//已支付
                financeTradeReceivableService.update_finance_trade_receivable(ftr);
            }
        }
        trb.setFinished_amount(tol_amount - end_amount);
        //更新
        if(tol_amount < trb.getFinished_amount()){
            //异常
            return failed(ErrorCode.SYS_FAIL);
        }
        financeTradeDetailService.update_finance_trade_details(trb);

        return success(null);
    }


    /**
     * 券支付
     */
    public Integer coupons_on_use(String coupons_id, String fund_type, Integer totol_value, BigInteger ftr_detail_id, BigInteger ftr_id, Integer user_id, GoodsInfo gInfo,boolean flag){
        Coupons coupons = couponsService.select_coupons(Integer.valueOf(coupons_id));
        if(coupons == null){
            Log.d("对应的券信息不存在" + coupons_id);
            return totol_value;
        }
        if(!user_id.equals(coupons.getBind_user_id())){
            //表示该券未绑定到当前用户
            Log.d("该券未绑定到当前用户，券id：" + coupons_id);
            return totol_value;
        }
        boolean cbc = couponsService.check_coupons(coupons,fund_type);

        //判断券业务限制条件
        boolean check_restrict = restrictedConditionService.check_restrict("COUPON",coupons.getId().toString(),"USE",user_id,gInfo);

        if(cbc && check_restrict){
            //券状态可用
            CouponBatch coupon_batch = couponBatchService.select_coupon_batch(coupons.getBatch_id());
            if(coupon_batch != null){
                CouponType coupon_type = couponTypeService.select_coupon_type(Integer.valueOf(coupon_batch.getType()));
                if(coupon_type == null){
                    //券种类不存在
                    return totol_value;
                }
                if("GOODS".equals(fund_type)){
                    //商品及商品种类允许的券种类            校验currency_code和 account_code
//                                GoodsInfo gInfo = goodsInfoService.select_goodsInfo_by_id(bean.getGoods_id().longValue());
                    //判断该券是否被商品及商品种类允许使用
                    boolean coupon_status = goodsInfoService.check_coupon_goods(coupon_type,gInfo);
                    if(!coupon_status){
                        //商品及商品种类不允许使用该券
                        return totol_value;
                    }
                }
                //券的面额
                Integer face_value = coupon_batch.getFace_value();
                //扣除券面额剩余的待支付（加判断，比较金额大小）按券过期时间将近的优先使用
                //考虑可混合使用券
                if(totol_value >= face_value){
                    //满扣无剩余
                    totol_value = totol_value - face_value;//for循环可以叠加使用券
                    coupons.setWasted(0);//无剩余
                }else{
                    //消费totol_value，剩余face_value-totol_value
                    totol_value = 0;
                    coupons.setWasted(face_value-totol_value);
                }
                //flag 为false仅计算，不产生流水记录（仅计算）
                if(flag){
                    //更新券信息状态
                    coupons.setBind_user_id(user_id);
                    coupons.setBind_time(new Date());
                    coupons.setStatus(Constant.COUPONS_STATUS_FROZEN);//冻结中，订单中被使用
                    coupons.setTrade_id(ftr_detail_id);
                    couponsService.update_coupons(coupons);

                    //已使用的券生成已收已付记录
                    FinanceTradeReceived ftrd = financeTradeReceivedService.add_finance_trade_received(face_value,ftr_detail_id,ftr_id,Constant.FINANCE_STATUS_CREATED);
                    //创建已收已付款项的支付信息
                    financePaymentDetailService.add_finance_payment_detail(face_value,ftrd.getId(),user_id,coupons.getId().toString(),"COUPON");
                }
            }else{
                //券不可用——不享受券优惠抵扣
                return totol_value;
            }
        }else{
            //不可用
            Log.d(coupons_id + "券不可用，类型：" + fund_type);
            //券不可用——不享受券优惠抵扣
            return totol_value;
        }
        return totol_value;
    }
}
